from flask import current_app, render_template, session, jsonify, request

from info import constants
from info.models import User, News, Category
from info.modules.index import index_bp
from info.response_code import RET

@index_bp.route('/news_list')
def get_news_list():
    """获取新闻列表数据后端接口"""
    """1获取参数
        cid:分类id值 p: 当前页码 默认值为：1 per_page:每一页多少条新闻数据 默认值：10条
        2 参数校验
            非空判断
            将参数进行int强制类型转换
        3逻辑处理
            新闻的分类id等于cid ,分页查询，新闻创建的时间降序排序
        4 返回值
            返回新闻列表数据
            """
    cid =request.args.get("cid")
    p = request.args.get("p",1)
    per_page = request.args.get("per_page",10)

    if not cid:
        return jsonify(errno=RET.PARAMERR,errmsg="参数不足")
    try:
        cid = int(cid)
        p = int(p)
        per_page=int(per_page)
    except Exception as e:
        p = 1
        per_page = 10
        current_app.logger.error(e)
    news_list = []
    current_page = 1
    total_page = 1
    filter_list = []
    if cid!=1:
        filter_list.append(News.category_id==cid)


    try:
        # paginate = News.query.filter(News.category_id==cid).order_by(News.create_time.desc()).paginate(p,per_page,False)
        paginate = News.query.filter(*filter_list).order_by(News.create_time.desc()) \
            .paginate(p, per_page, False)
        news_list= paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "查询用户对象异常")
    news_dict_list = []
    for news in news_list if news_list else []:
        news_dict_list.append(news.to_dict())
    data = {
        "news_list":news_dict_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return jsonify(errno = RET.OK,errmsg = "查询新闻列表数据成功",data = data)

@index_bp.route('/')
def index():

    # 获取session中的用户id
    user_id = session.get('user_id')
    #根据user_id 查询当前用户对象
    user = None #type:User
    if user_id:
        try:
            user = User.query.get(user_id)
            print(user)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="查询用户对象异常")
    #将用户对象转换成字典
    user_dict = user.to_dict() if user else None
    #===============  查询新闻的点击排行数据=========
    try:

       news_rank_list= News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "查询点击排行新闻对象异常")
    """    if news_rank_list:
        for news in news_rank_list:
            news_dict = news.to_dict()
            news_rank_list.append(news_dict)"""

    newsrank_rank_list = []
    for news in news_rank_list if news_rank_list else []:
        newsrank_rank_list.append(news.to_dict())


    #+++++++++++++++++++ 3.查询新闻的分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg = "查询用户对象异常")
    category_dict_list = []
    for category in categories if categories else []:
        category_dict = category.to_dict()
        category_dict_list.append(category_dict)

    data = {"user_info":user_dict,
            "click_news_list":newsrank_rank_list,
            "categories":category_dict_list}
    print(data)
    #组织返回数据
    return render_template("news/index.html",data = data)

@index_bp.route('/favicon.ico')
def get_facicon():
    "返回网站图标"

    return current_app.send_static_file("news/favicon.ico")